//
//  ShoppingCartViewController.m
//  ChineseCollegeStudentsNetwork
//
//  Created by LeGuo on 5/20/18.
//  Copyright © 2018 刘喆. All rights reserved.
//

#import "ShoppingCartViewController.h"
#import "ShoppingCartTableViewCell.h"
#import "AddNewConsigneeAddressViewController.h"
#import "ShopCartBottomBarView.h"
#import "ShopingCartModel.h"
#import "ShoppingCartDetailVC.h"

@interface ShoppingCartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) ShopCartBottomBarView *bottomBarView;
/** 订单详情列表 */
@property(nonatomic, strong) UITableView *orderDetailList;

@property(nonatomic, copy)NSString *type;
@property (nonatomic, strong) UIBarButtonItem *managementBar;
@property (nonatomic, strong) NSMutableArray<ShopingCartModel *> *listData;
@property (nonatomic, copy)NSString *totalStr;
@property (nonatomic)CGFloat tempStr;
@property (nonatomic)CGFloat tempStr2;
@property (nonatomic)CGFloat temp;
@end

@implementation ShoppingCartViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"购物车";
    self.view.backgroundColor = UIColorWithRGB(245, 245, 245);
    _managementBar = [[UIBarButtonItem alloc] initWithTitle:@"管理" style:UIBarButtonItemStylePlain target:self action:@selector(managementItemClicked)];
    self.navigationItem.rightBarButtonItem = _managementBar;
    
    _listData = [NSMutableArray array];
    [self loadData];

    [self.view addSubview:self.bottomBarView];
    [self loadLayout];
}

#pragma mark - Lazy Loading


- (UITableView *)orderDetailList {
    
    if (!_orderDetailList) {
        
        _orderDetailList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _orderDetailList.backgroundColor = [UIColor clearColor];
        _orderDetailList.showsVerticalScrollIndicator = NO;
        _orderDetailList.showsHorizontalScrollIndicator = NO;
        _orderDetailList.separatorStyle = UITableViewCellSeparatorStyleNone;
        _orderDetailList.delegate = self;
        _orderDetailList.dataSource = self;

        
        [self.view addSubview:_orderDetailList];
    }
    return _orderDetailList;
}

- (ShopCartBottomBarView *)bottomBarView {
    
    if (!_bottomBarView) {
        
        _bottomBarView = [[ShopCartBottomBarView alloc] initWithFrame:CGRectZero];
        [_bottomBarView.checkButton addTarget:self action:@selector(checkButtonclick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBarView.accountButton addTarget:self action:@selector(accountBtnAction:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _bottomBarView;
}


#pragma mark - Layout

- (void)loadLayout {
    
    [self.bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.bottom.equalTo(self.view);
        make.height.mas_equalTo(@49);
    }];
    
    [self.orderDetailList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.bottomBarView.mas_top);
    }];
    

}

- (void)loadData {
    [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiCartGet" params:@{@"siteId":@"32"}.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        
        
//        _listData = [NSMutableArray array]
        _listData = [ShopingCartModel mj_objectArrayWithKeyValuesArray:response[@"cartInfoList"]];
      
      
        [self.orderDetailList reloadData];

        NSLog(@"---------%@",response);
    } failure:^{
        NSLog(@"sjasj");
    }];
}

#pragma mark - UITableView && UITableViewDatasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _listData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (_listData.count != 0) {
        ShopingCartModel *model = _listData[indexPath.section];
        ShoppingCartTableViewCell *shopCell = [tableView dequeueReusableCellWithIdentifier:@"shopCell"];
        
        if (!shopCell) {
            shopCell = [[ShoppingCartTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"shopCell"];
        }
        
        shopCell.model = model;
    
        
        shopCell.reloadTableView = ^(ShopingCartModel *model) {
            _temp = 0;
            for (int i = 0; i < self.listData.count; i++) {
                ShopingCartModel *model = _listData[i];
                CGFloat str = [model.count floatValue] * [model.fee floatValue];
                
                _temp = str + _temp;
                
            }
            if (model.isSelected) {
                
            }else{
                _bottomBarView.checkButton.selected = NO;
            }
            _tempStr2 = 0;
            for (int i = 0; i < self.listData.count; i++) {
                ShopingCartModel *model2 = _listData[i];
                if (model2.isSelected) {
                    
                    CGFloat str = [model2.count floatValue] * [model2.fee floatValue];
                    
                    _tempStr2 = str + _tempStr2 ;
                }
                
                
            }
            
            _bottomBarView.priceLabel.text = [NSString stringWithFormat:@"¥%.2f",_tempStr2];
            
            if (_temp == _tempStr2) {
                _bottomBarView.checkButton.selected = YES;
            }
        };
        
        
        
        
        return shopCell;
        
    }else{
        ShoppingCartTableViewCell *shopCell = [tableView dequeueReusableCellWithIdentifier:@"shopCell"];
        
        if (!shopCell) {
            shopCell = [[ShoppingCartTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"shopCell"];
        }
        
//        shopCell.model = model;
        return shopCell;
        
    }
    
    
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 15;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120.0f;
}


#pragma mark - BarButtonItem Action

- (void)managementItemClicked {
    if ([_type isEqualToString:@"1"]) {

        _managementBar.title = @"管理";
        _bottomBarView.totalLabel.hidden = NO;
        _bottomBarView.priceLabel.hidden = NO;
        [_bottomBarView.accountButton setTitle:@"结算" forState:UIControlStateNormal];
        _type = @"2";
    }else{

        _managementBar.title = @"取消";
        _bottomBarView.totalLabel.hidden = YES;
        _bottomBarView.priceLabel.hidden = YES;
        [_bottomBarView.accountButton setTitle:@"删除" forState:UIControlStateNormal];
        _type = @"1";
    }
}

- (void)checkButtonclick:(UIButton *)sender {
    sender.selected = !sender.selected;
    for (ShopingCartModel *model in self.listData) {
        if (sender.selected) {
            model.isSelected = YES;
          
          
        }else{
            model.isSelected = NO;
           
        }
        
    }
    
    if (sender.selected) {
         for (ShopingCartModel *model in self.listData) {
             _bottomBarView.priceLabel.text = [NSString stringWithFormat:@"¥%.2f",[model.count floatValue] * [model.fee floatValue]];
         }
        for (int i = 0; i < self.listData.count; i++) {
            ShopingCartModel *model = _listData[i];
            CGFloat str = [model.count floatValue] * [model.fee floatValue];
            
            _tempStr = str + _tempStr;
           
        }
         _bottomBarView.priceLabel.text = [NSString stringWithFormat:@"¥%.2f",_tempStr];
    }else{
        _tempStr = 0;
         _bottomBarView.priceLabel.text = @"¥0";
    }
    
    
    [self.orderDetailList reloadData];
    
}


- (void)accountBtnAction:(UIButton *)sender {
    if ([_type isEqualToString:@"1"]) {
        //删除
        
    } else {
        //结算
        NSMutableArray *modelsArr = [NSMutableArray array];
        [_listData enumerateObjectsUsingBlock:^(ShopingCartModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.isSelected) {
                [modelsArr addObject:obj];
            }
        }];
        
        if (modelsArr.count == 0) {
            return;
        }

        ShoppingCartDetailVC *odVC = [[ShoppingCartDetailVC alloc] init];
        odVC.modelsArr = [modelsArr copy];
        [self.navigationController pushViewController:odVC animated:YES];

        
    }
}

@end
